//
//  XWOAuthViewController.swift
//  新浪 weibo
//
//  Created by xuwei on 16/1/21.
//  Copyright © 2016年 xuwei. All rights reserved.
//

import UIKit
import SVProgressHUD

let WB_CLIENT_ID = "97904202"

let WB_REDIRECT_URL = "http://www.itheima.com/"

let WB_CLIENT_SECRET = "36451ca0ef5c4abe54228d83241f4ce5"

class XWOAuthViewController: UIViewController {
    private lazy var webView : UIWebView = {
        let webView = UIWebView()
        webView.delegate = self
        return webView
    }()
    
    override func loadView() {
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_CLIENT_ID)&redirect_uri=\(WB_REDIRECT_URL)"
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
        
        
    }
    
    private func setupUI(){
        
        navigationItem.title = "新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(imgNamed: nil, title: "取消", target: self, action: "cancel")
        navigationItem.rightBarButtonItem = UIBarButtonItem(imgNamed: nil, title: "自动填充", target: self, action: "autoFill")
        
    }
    
    @objc private func cancel(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    @objc private func autoFill(){
        let jsString = "document.getElementById('userId').value='13718607632';document.getElementById('passwd').value='110011.xw'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
}

extension XWOAuthViewController : UIWebViewDelegate{
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        
        guard let url = request.URL else{
            return false
        }
        
        if !url.absoluteString.hasPrefix(WB_REDIRECT_URL)
        {
            return true
        }
        
        let query = url.query!
        
        if !query.hasPrefix("code="){
            return true
        }
        
        let code = query.substringFromIndex("code=".endIndex)
        
        XWUserAccountViewModel.shareViewModel.loadAccessToken(code){ (isSuccess)->() in
            if isSuccess {
                print("登陆成功，跳转界面")
            }
            else{
                SVProgressHUD.showErrorWithStatus("登录失败")
            }

        }
        
        return false
    }
}














